package cn.phecda.boot.data.mybatis.configuration;

import cn.phecda.boot.data.mybatis.plus.SnowflakeIdentifierGenerator;
import cn.phecda.boot.data.mybatis.plus.EntityMetaObjectHandler;
import cn.phecda.boot.data.mybatis.properties.DataMybatisProperties;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <p> Data JPA 模块配置 </p>
 *
 * @author : wanpinwei
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(DataMybatisProperties.class)
public class DataMybatisPlusConfiguration {

    @PostConstruct
    public void postConstruct() {
        log.info("|Phecda Boot Data|- Data Mybatis Plus Configuration");
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(DataMybatisProperties properties) {
        final MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        // 分页
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        // 乐观锁
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(properties.getDbType()));
        // 阻断攻击Sql解析器
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());

        log.trace("|Phecda Boot Data|- Mybatis Plus Interceptor");
        return interceptor;
    }

    @Bean
    public SnowflakeIdentifierGenerator snowflakeIdentifierGenerator() {
        SnowflakeIdentifierGenerator generator = new SnowflakeIdentifierGenerator();
        log.trace("|Phecda Boot Data|- Snowflake Identifier Generator");
        return generator;
    }


    @Bean
    public EntityMetaObjectHandler entityMetaObjectHandler() {
        EntityMetaObjectHandler handler = new EntityMetaObjectHandler();
        log.trace("|Phecda Boot Data|- Entity Meta ObjectHandler");
        return handler;
    }
}
